// pages/login/index.js
//获取应用实例
const app = getApp()
import {
  urls
} from '../../api/urls'
import Dialog from '../../dist/dialog/dialog';
import {
  checkLogin,
  getMobile,
  check_mobile,
  get_para,
  user_log_record,
  save_userinfo
} from '../../api/request'
Page({
  data: {
    appid: '',
    secret: '',
    isFx: false, //判断是否是分享进来的
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    isSq: false, //是否授权    
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    userStatus: '',
    mobile: ''
  },

  onLoad: function (e) {},

  getUserInfo: function (e) {
    console.log(e)
    if (e.detail.errMsg == "getUserInfo:fail auth deny") { //用户拒绝
      wx.showModal({
        title: '提示',
        content: '微信小程序需要你授权才能继续参与小区业主投票',
      })

    } else {
      app.globalData.userInfo = e.detail.userInfo
      this.setData({
        userInfo: e.detail.userInfo,
        hasUserInfo: true
      })
      wx.setStorageSync('userInfo', e.detail.userInfo)
      //记录用户完整信息至数据库
      console.log('------ save openid=' + app.globalData.cur_my_openid + '----nikename=' + this.data.userInfo.nickName + '----' + this.data.userInfo.gender)
      var data = {
        para: [app.globalData.cur_my_openid,
          this.data.userInfo.avatarUrl,
          this.data.userInfo.city,
          this.data.userInfo.country,
          this.data.userInfo.gender,
          this.data.userInfo.language,
          this.data.userInfo.nickName,
          this.data.userInfo.province
        ]
      }

      save_userinfo(data).then(res => {
        console.log('----save user info ret=' + res.data[0].ERRORCODE + '-----')
      })
    }
  },

  //获取手手机号
  getPhoneNumber: function (e) {
    console.log('--------开始获取手机号码[openid=', app.globalData.cur_my_openid, ']--------')
    let _this = this;
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      wx.cloud.callFunction({
        name: 'getMobile',
        data: {
          weRunData: wx.cloud.CloudID(e.detail.cloudID),
        }
      }).then(res => {
        console.log('------ok---------res.result.event.weRunData=',res.result.event.weRunData)
        _this.setData({
          mobile: res.result.event.weRunData.data.purePhoneNumber,
        })
        _this.check_mobile(app.globalData.cur_my_openid, _this.data.mobile)

      }).catch(err => {
        console.log('-------------2-------',err);
        console.log('-------------2-------res=',res);
        wx.showModal({
          title: '手机号码授权失败',
          content: err,
        })
        _this.check_mobile(app.globalData.cur_my_openid, '')
      });

    } else {
      wx.showModal({
        title: '获取手机号码授权失败',
        content: e.detail.errMsg,
      })
      console.log('-------------3-------',e.detail.errMsg);
      _this.check_mobile(app.globalData.cur_my_openid, '')
    }
  },
  //手机号实名认证
  check_mobile(openid, mobile) {
    const _this = this
    console.log('-----check_mobile(openid=[', openid, '],mobile=[', mobile, '])---------')
    var data = {
      para: [openid, mobile]
    }
    check_mobile(data).then(res => {
      console.log('----check_ret=' + res.data[0].ERRORCODE + '------')

      if (res.data[0].ERRORCODE == '0') {
        //手机认证未通过        
        if (res.data[0].ERRORCODE == '0') wx.setStorageSync('certification_status', false)
        console.log('------手机号码[', mobile, ']实名认证未通过，临时转主页面-----')
        wx.setStorageSync('certification_status', false)
        app.globalData.phoneNumber = mobile
        app.globalData.cur_room_code = '请实名认证'

        wx.showModal({
          title: '手机实名认证失败',
          confirmText: "确定",
          showCancel: false, //是否显示取消按钮
          content: '请改用身份证等证件实名认证',
        })

      } else {
        console.log('------手机号码[', res.data[0].MOBILE, ']实名认证通过，转主页面-----')
        wx.setStorageSync('certification_status', true)
        //更新全局变量
        app.globalData.phoneNumber = res.data[0].MOBILE
        app.globalData.cur_room_code = res.data[0].ROOM_CODE
        app.globalData.cur_my_name = res.data[0].ROOM_NAME
        app.globalData.cur_property_code = res.data[0].PROPERTY_CODE
        app.globalData.cur_property_name = res.data[0].PROPERTY_NAME
        app.globalData.cur_job = res.data[0].CUR_JOB
        app.globalData.cur_street_name = res.data[0].STREET_NAME
        wx.setStorageSync('openid', app.globalData.cur_my_openid)
        wx.showModal({
          title: '手机号实名认证成功',
          confirmText: "确定",
          showCancel: false, //是否显示取消按钮
          content: '你的微信号已绑定到' + app.globalData.cur_property_name + '(' + app.globalData.cur_room_code + ')',
        })

      }
      wx.switchTab({
        url: '/pages/home/index',
        success(res) {
          let page = getCurrentPages().pop();
          if (page == undefined || page == null) {
            return
          }

          page.home_flush(); //刷新主页面

        }
      })
      _this.user_log_record(openid, app.globalData.cur_my_name, '', '', app.globalData.cur_property_code, app.globalData
        .cur_property_name, '1', '12', '1')
    })
  },
  //小程序关键使用行为记录保存
  user_log_record(cur_openid, cur_username, from_openid, from_username, from_property_code, from_property_name,
    share_channel, log_type, log_msg) {
    var data = {
      para: '["' + cur_openid + '","' + cur_username + '","' + from_openid + '","' + from_username + '","' +
        from_property_code + '","' + from_property_name + '","' + share_channel + '","' + log_type + '","' + log_msg +
        '"]',
    }
    user_log_record(data).then(res => {
      console.log('-----user_log_record:', res.data[0].ERRORMSG)
    })
  },
})